<template>
    <div>
        <el-button type="primary" @click="showForm = true">新增</el-button>
        <el-table :data="tableData" style="width: 100%; margin-top: 16px;">
            <el-table-column v-for="field in model.fields" :key="field.name" :prop="field.name" :label="field.label" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="edit(scope.row)">编辑</el-button>
                    <el-button @click="remove(scope.row)" type="danger">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog v-model="showForm" title="编辑/新增">
            <DynamicForm v-if="showForm" :modelName="modelName" :id="editId" @success="onSuccess" />
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import DynamicForm from './DynamicForm.vue'

const props = defineProps({ modelName: String })
const model = ref({ fields: [] })
const tableData = ref([])
const showForm = ref(false)
const editId = ref(null)

const loadModel = async () => {
    model.value = await axios.get(`/metadata/models/${props.modelName}`).then(res => res.data)
}
const loadData = async () => {
    tableData.value = await axios.get(`/data/${props.modelName}`).then(res => res.data)
}

onMounted(async () => {
    await loadModel()
    await loadData()
})

const edit = row => {
    editId.value = row.id
    showForm.value = true
}
const remove = async row => {
    await axios.delete(`/data/${props.modelName}/${row.id}`)
    await loadData()
}
const onSuccess = async () => {
    showForm.value = false
    editId.value = null
    await loadData()
};
</script>